#!/bin/bash

USE_ROOT=false
USER=`whoami`
USER_SHELL="/bin/bash"
SAME_USER=true
NUM_PROCS=-j2
DIR=`pwd`

# We need to resolve various incompatibilities between versions of
# XCode and gcc here. Whenever we're using XCode 3, we want to use gcc
# 4.0 even if 4.2 is available. Once we hit XCode 4, we start using
# 4.2. Since we struggle with all the various configs, we sanity check
# everything about these combinations.
xcode_3=`xcodebuild -version | grep "Xcode 3"`
xcode_4=`xcodebuild -version | grep "Xcode 4"`
gcc_40_path=`which gcc-4.0`
gcc_42_path=`which gcc-4.2`
gpp_40_path=`which g++-4.0`
gpp_42_path=`which g++-4.2`
default_gcc_40=`/usr/bin/gcc --version | grep gcc-4[.]0`
default_gcc_42=`/usr/bin/gcc --version | grep gcc-4[.]2`
if [ "$xcode_4" != "" ]; then
    # We can also use the default gcc in this case because it isn't
    # labelled as 4.2
    if [ "$gcc_42_path" != "" -o "$default_gcc_42" != "" ]; then
        GCC_VER=4.2
        GCC_PATH=$gcc_42_path
        GPP_PATH=$gpp_42_path
        if [ "$GCC_PATH" == "" ]; then
            GCC_PATH="/usr/bin/gcc"
            GPP_PATH="/usr/bin/g++"
        fi
        platform="x86_64"
    else
        echo "Unsupported configuration -- Xcode 4 but can't find gcc-4.2"
        exit 1
    fi
elif [ "$xcode_3" != "" ]; then
    if [ "$gcc_40_path" != "" ]; then
        GCC_VER=4.0
        GCC_PATH=$gcc_40_path
        GPP_PATH=$gpp_40_path
        platform="i386"
    else
        echo "Unsupported configuration -- Xcode 3 but can't find gcc-4.0"
        exit 1
    fi
else
    echo "Unsupported configuration -- couldn't find XCode 3 or 4."
    exit 1
fi

if [ -e /Developer/SDKs/MacOSX10.5.sdk ] ; then
    SDK_DIR="/Developer/SDKs/MacOSX10.5.sdk"
    SDK_VER=10.5
else
    SDK_DIR="/Developer/SDKs/MacOSX10.6.sdk"
    SDK_VER=10.6
fi

echo "--------------------------------"
echo "Build environment summary:"
echo "GCC Version: $GCC_VER"
echo "GCC Path: $GCC_PATH, $GPP_PATH"
echo "Architecture: $platform"
echo "SDK Version: $SDK_VER"
echo "SDK Directory: $SDK_DIR"
echo "--------------------------------"
echo

# Force to 32bit always for now
platform="i386"

WITH_BOOST=false
WITH_FREEIMAGE=false
WITH_SDL=false
WITH_OGRE=false
WITH_CHROMIUM=false
WITH_V8=false
WITH_PCRE=false
WITH_OPENCOLLADA=false
WITH_NVTT=false
WITH_SQLITE=false
WITH_PKGCONFIG=false
WITH_PROTOBUFS=false
WITH_ANTLR=false
WITH_GSL=false
WITH_BULLET=false
WITH_THRIFT=false
WITH_LIBCASSANDRA=false
WITH_YASM=false
WITH_FFMPEG=false

################################################################################################################################
# Define a function to execute a command as a different user if necessary
################################################################################################################################

function user_eval {
    if $SAME_USER ; then
        pushd "${DIR}" >/dev/null
        $USER_SHELL -c "$1"
        RET=$?
        popd >/dev/null
        return $RET
    else
        su - $USER -s /usr/bin/env -- $USER_SHELL -c "export OLDPATH='$OLDPATH'; export PATH='$PATH'; cd ${DIR}; $1"
        return $?
    fi
}

function make_symlink {
    TARGET=$1
    LINK_NAME=$2

    user_eval "cd ${DIR}; rm -f $LINK_NAME; ln -fs $TARGET $LINK_NAME && (touch -m $LINK_NAME || true)"
}

# Unlike make_symlink, this will delete the contents, if this is not a symlink.
function clean_dir {
    DIRECTORY=$1
    user_eval "cd ${DIR}; rm -f ${DIRECTORY} 2>/dev/null; rm -rf ${DIRECTORY}"
}

################################################################################################################################
# Parse command-line arguments
################################################################################################################################

until [ -z "$1" ] # until all parameters used up
do
    case "$1" in
        boost)
            SHOW_USAGE=false
            WITH_BOOST=true
            ;;
        freeimage)
            WITH_FREEIMAGE=true
            SHOW_USAGE=false
            ;;
        sdl)
            WITH_SDL=true
            SHOW_USAGE=false
            ;;
        ogre)
            WITH_OGRE=true
            SHOW_USAGE=false
            ;;
        chromium)
            WITH_CHROMIUM=true
            ;;
        v8)
            WITH_V8=true
            ;;
        pcre)
            WITH_PCRE=true
            SHOW_USAGE=false
	    ;;
        opencollada)
            WITH_OPENCOLLADA=true
            SHOW_USAGE=false
            ;;
        nvtt)
            WITH_NVTT=true
            SHOW_USAGE=false
            ;;
        sqlite)
            WITH_SQLITE=true
            SHOW_USAGE=false
            ;;
        pkgconfig)
            WITH_PKGCONFIG=true
            SHOW_USAGE=false
            ;;
        pkg-config)
            WITH_PKGCONFIG=true
            SHOW_USAGE=false
            ;;
        protobufs)
            WITH_PROTOBUFS=true
            SHOW_USAGE=false
            ;;
        antlr)
            WITH_ANTLR=true
            SHOW_USAGE=false
            ;;
        gsl)
            WITH_GSL=true
            SHOW_USAGE=false
            ;;
        bullet)
            WITH_BULLET=true
            SHOW_USAGE=false
            ;;
        thrift)
            WITH_THRIFT=true
            SHOW_USAGE=false
            ;;
        libcassandra)
            WITH_LIBCASSANDRA=true
            SHOW_USAGE=false
            ;;
        yasm)
            WITH_YASM=true
            SHOW_USAGE=false
            ;;
        ffmpeg)
            WITH_FFMPEG=true
            SHOW_USAGE=false
            ;;

        -j* ) NUM_PROCS="$1" ;;
    esac
    shift
done

################################################################################################################################
# Install Boost
################################################################################################################################

if [[ -n "$INSTALLED_BOOST" ]] ; then
    make_symlink $INSTALLED_BOOST installed-boost
    WITH_BOOST=false
fi
if $WITH_BOOST ; then
    echo "Installing Boost..."
    clean_dir installed-boost
    # The weird symlinking at the end is for libcassandra. Since we only specify boost prefix and
    # this install is giving installed-boost/include/boost-1_45/boost/ instead of the normal
    # installed-boost/include/boost/, we force an normal layout as well so libcassandra can find it.
    BOOST_VERSION="1_46_1"
    BOOST_VERSION_DOT="1.46.1"
    user_eval "cd ${DIR} &&
               [ -e boost_${BOOST_VERSION}.tar.bz2 ] || curl -o boost_${BOOST_VERSION}.tar.bz2 -L http://downloads.sourceforge.net/project/boost/boost/1.46.1/boost_${BOOST_VERSION}.tar.bz2 &&
               tar -jxf boost_${BOOST_VERSION}.tar.bz2 &&
               cd boost_${BOOST_VERSION} &&
               PATH=${DIR}/wrapper:${PATH} ./bootstrap.sh --with-toolset=gcc --without-icu --with-libraries=system,program_options,thread,filesystem,regex,date_time,iostreams --prefix=${DIR}/installed-boost &&
               PATH=${DIR}/wrapper:${PATH} ./bjam cflags=\"-m32 -fvisibility=hidden\" cxxflags=\"-m32 -fvisibility=hidden\" address-model=32 architecture=x86 instruction-set=i686 threading=multi --layout=tagged --build-type=complete toolset=darwin install &&
               cd ${DIR}/installed-boost/include/ &&
               ln -s boost-1_45/boost boost" || \
    FAILED="$FAILED boost"
fi

################################################################################################################################
# Install FreeImage
################################################################################################################################

if [[ -n "$INSTALLED_FREEIMAGE" ]] ; then
    make_symlink $INSTALLED_FREEIMAGE installed-freeimage
elif $WITH_FREEIMAGE; then
    echo "Installing FreeImage..."

    # tr is necessary because the zip file uses CRLF line endings,
    # and 'patch' has no option to ignore line endings! Why?!
    # Note that "tr" has a bug on mac 10.5 if export LC_ALL=C is not used.
    user_eval "cd ${DIR};
               [ -e FreeImage3100.zip ] || curl -o FreeImage3100.zip -L http://downloads.sourceforge.net/project/freeimage/Source%20Distribution/3.10.0/FreeImage3100.zip &&
               unzip -o FreeImage3100.zip &&
               cd FreeImage &&
               export LC_ALL=C &&
               tr -d '\\r' < Source/FreeImage/PluginBMP.cpp > x &&
               mv x Source/FreeImage/PluginBMP.cpp &&
               tr -d '\\r' < Source/Metadata/Exif.cpp > x &&
               mv x Source/Metadata/Exif.cpp &&
               patch -p1 < ../FreeImage64bit.patch &&
               cp Makefile.osx Makefile.osx.orig &&
               cp Makefile.osx Makefile.osx.old &&
               cat Makefile.osx.orig | sed -e s@/Developer/SDKs/MacOSX10.4u.sdk@$SDK_DIR@ > Makefile.osx.p1 &&
               cat Makefile.osx.p1 | sed -e s@i386@x86_64@g > Makefile.osx.p2 &&
               cat Makefile.osx.p2 | sed -e s@I386@X86_64@g > Makefile.osx.p3 &&
               cat Makefile.osx.p3 | sed -e s@ppc@i386@g > Makefile.osx.p4 &&
               cat Makefile.osx.p4 | sed -e s@PPC@I386@g > Makefile.osx.p5 &&
               cat Makefile.osx.p5 | sed -e s@/Developer/SDKs/MacOSX10.3.9.sdk@$SDK_DIR@ > Makefile.osx.p6 &&
               cat Makefile.osx.p6 | sed -e s@gcc-4.0@${GCC_PATH}@ > Makefile.osx.p7 &&
               cat Makefile.osx.p7 | sed -e s@g++-4.0@${GPP_PATH}@ > Makefile.osx &&
               make $NUM_PROCS &&
               make dist &&
               (cd ..;mkdir lib||echo exists;mkdir include||echo exists ;
               cp FreeImage/Dist/* ${DIR}/lib;
               cp FreeImage/Dist/* ${DIR}/include )" && \
    make_symlink FreeImage installed-freeimage || \
    FAILED="$FAILED freeimage"
fi

################################################################################################################################
# Install SDL
################################################################################################################################

if [[ -n "$INSTALLED_SDL" ]] ; then
    make_symlink $INSTALLED_SDL installed-sdl
elif $WITH_SDL; then
    echo "Installing SDL..."
    # NOTE: Do not use NUM_PROCS on the make command. SDL's
    # build system doesn't handle this properly and
    # sometimes breaks
    user_eval "cd ${DIR} &&
               tar -zxf SDL-1.3.0-4685.tar.gz &&
               cd SDL-1.3.0-4685 &&
               patch -p0 < ../SDLkeymouse.patch &&
               patch -p0 < ../SDLatomic.patch &&
               patch -p0 < ../SDLx11keyrepeat.patch &&
               patch -p0 < ../SDLwindowfocus.patch &&
               patch -p0 < ../SDLmackeyevent.patch &&
               patch -p0 < ../SDLmacwminfo.patch &&
               patch -p0 < ../SDL_mac_gui_release.patch &&
               patch -p0 < ../SDL_mac_audio.patch &&
               PATH=${DIR}/wrapper:${PATH} CFLAGS=\"-m32 -arch i386\" CXXFLAGS=\"-m32 -arch i386\" LDFLAGS=\"-m32 -arch i386\" ./configure --prefix=${DIR}/installed-sdl --without-x --disable-cdrom &&
               make &&
               make install" || \
    FAILED="$FAILED sdl"
fi


################################################################################################################################
# Install Ogre
################################################################################################################################

if [[ -n "$INSTALLED_OGRE" ]] ; then
    make_symlink $INSTALLED_OGRE installed-ogre
elif $WITH_OGRE ; then
    echo "Installing Ogre..."
    clean_dir installed-ogre
    # Note: It seems that background loading is broken in this Ogre
    # (hanging X on Linux), but we also don't seem to be using it. To
    # try enabling it, add -DOGRE_CONFIG_THREADS=2
    user_eval "cd ${DIR} &&
               ([ -e ogre_src_v1-7-2.tar.bz2 ] || curl -L -o ogre_src_v1-7-2.tar.bz2 http://downloads.sourceforge.net/project/ogre/ogre/1.7/ogre_src_v1-7-2.tar.bz2) &&
               tar -xjf ogre_src_v1-7-2.tar.bz2 &&
               patch -p0 < ogre_macapi.patch &&
               patch -p0 < ogre_sampler.patch &&
               patch -p0 < ogre_mac_zzip.patch &&
               patch -p0 < ogre_big_endian.patch &&
               cd ogre_src_v1-7-2 &&
               sed -i .bak -e 's/[iI][fF] *(OGRE_BUILD_PLATFORM_IPHONE AND.*CMAKE_VERSION.*)/IF(FALSE)/' CMakeLists.txt &&
               sed -e 's/-xgcc/-gcc/' < \"\$(cmake --system-information | grep CMAKE_ROOT | cut -d '\"' -f 2)/Modules/FindBoost.cmake\" > CMake/FindBoost.cmake &&
               ([ -e build ] || mkdir build) && cd build &&
               cmake -GXcode -DOGRE_BUILD_SAMPLES=FALSE -DOGRE_CONFIG_THREADS=0 -DOGRE_CONFIG_ALLOCATOR=2 -DCMAKE_INSTALL_PREFIX=${DIR}/installed-ogre \
                   -DBoost_FIND_VERSION_EXACT=true -DBoost_FIND_VERSION_MAJOR=1 -DBoost_FIND_VERSION_MINOR=45 -DBOOST_ROOT=${DIR}/installed-boost \
                   -DFreeImage_INC_SEARCH_PATH=${DIR}/include -DFreeImage_LIB_SEARCH_PATH=${DIR}/lib \
                   .. &&
               xcodebuild -configuration RelWithDebInfo &&
               xcodebuild -configuration RelWithDebInfo -target install &&
               cd .. && \
               ([ -e Frameworks ] || mkdir Frameworks)" && \
		   mkdir -p ${DIR}/Frameworks && \
		   cd ${DIR}/Frameworks && ln -fs ../installed-ogre/lib/RelWithDebInfo/Ogre.framework Ogre.framework || \
		   FAILED="$FAILED ogre"
# Note that we used to have something like
#		   cd ${DIR}/installed-ogre && ln -fs build/lib/RelWithDebInfo OgrePlugins || \
# but we no longer need it because things get installed into installed-ogre/lib and we have that offset in the OgreSystem loading code.
fi

################################################################################################################################
# Install Chromium
################################################################################################################################

if $WITH_CHROMIUM ; then
    BERKELIUM_ROOT="${DIR}/../externals/berkelium"
    SIRIKATA_BUILD_ROOT="${DIR}/../build/cmake"

    BUILD_CHROMIUM_PARAMS="${NUM_PROCS} --build-dir chromium --install-dir installed-chromium --app-dir ${SIRIKATA_BUILD_ROOT} --patch-dir ${BERKELIUM_ROOT}/patches"
    if $USE_ROOT; then
        BUILD_CHROMIUM_PARAMS="${BUILD_CHROMIUM_PARAMS} --use-root"
    fi
    if $WITH_CHROMIUMDEPS; then
        BUILD_CHROMIUM_PARAMS="${BUILD_CHROMIUM_PARAMS} --deps"
    fi

    user_eval "${BERKELIUM_ROOT}/util/build-chromium.sh ${BUILD_CHROMIUM_PARAMS}" || \
        FAILED="$FAILED chromium"
fi


############################################################
# Install V8
############################################################

if $WITH_V8 ; then
    echo "Installing V8..."

    bitness_flags=""
    if [ x"$platform" = x"x86_64" ]; then
	bitness_flags="arch=x64"
    fi

    SCONS_PATH=""
    if [ ! `which scons` ]; then
        if [ ! -e '${DIR}/installed-scons/bin/scons' ]; then
            user_eval "cd ${DIR} && tar -zxf scons-1.3.0.tar.gz \
                       && cd scons-1.3.0 \
                       && python setup.py install --prefix=${DIR}/installed-scons" || \
            FAILED="$FAILED scons (for v8)"
        fi
        # Note that we include the : so that it works with an empty SCONS_PATH too
        SCONS_PATH="${DIR}/installed-scons/bin:"
    fi

    V8_VERSION="3.3.9.3"
    clean_dir v8
    clean_dir installed-v8
    user_eval "cd ${DIR} && \
                   svn checkout http://v8.googlecode.com/svn/tags/${V8_VERSION} v8 && \
                   cd v8 && \
                   svn revert -R . && \
                   patch -p0 < ../v8_install.patch && \
                   PATH=${SCONS_PATH}$PATH scons $NUM_PROCS ${bitness_flags} PREFIX=${DIR}/installed-v8 library install" || \
        FAILED="$FAILED v8"
fi


############################################################
# Install PCRE
############################################################

if [[ -n "$INSTALLED_PCRE" ]] ; then
    make_symlink $INSTALLED_PCRE installed-pcre
elif $WITH_PCRE ; then
    echo "Installing PCRE . . ."
    PCRE_VERSION="8.21"
    clean_dir pcre-${PCRE_VERSION}
    clean_dir installed-pcre
    user_eval "cd ${DIR} &&
               ( [ -e pcre-${PCRE_VERSION}.zip ] || curl -O ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-${PCRE_VERSION}.zip ) &&
               unzip pcre-${PCRE_VERSION}.zip &&
               cd pcre-${PCRE_VERSION} &&
               PATH=${DIR}/wrapper:${PATH} CFLAGS=\"-m32 -arch i386\" CXXFLAGS=\"-m32 -arch i386\" LDFLAGS=\"-m32 -arch i386\" ./configure --prefix=${DIR}/installed-pcre --with-pic &&
               make $NUM_PROCS &&
               make install" || \
    FAILED="$FAILED PCRE"
fi


# Install OpenCollada

if [[ -n "$INSTALLED_OPENCOLLADA" ]] ; then
    make_symlink $INSTALLED_OPENCOLLADA installed-opencollada
elif $WITH_OPENCOLLADA ; then
    echo "Installing OpenCollada . . ."
    clean_dir installed-opencollada
    user_eval "cd ${DIR} &&
               svn co -r788 http://opencollada.googlecode.com/svn/trunk opencollada &&
               cd opencollada &&
               ( patch -N -p0 < ${DIR}/opencollada_cmake_flags.patch || true ) &&
               ( patch -N -p0 < ${DIR}/opencollada_pcre_path_fix.patch || true ) &&
               PATH=${DIR}/wrapper:${PATH} CC=${DIR}/wrapper/gcc CXX=${DIR}/wrapper/g++ cmake -DCMAKE_INSTALL_PREFIX==${DIR}/installed-opencollada -DCMAKE_CXX_FLAGS=\"-g2 -m32 -arch i386 -fvisibility=hidden\" -DCMAKE_C_FLAGS=\"-g2 -m32 -arch i386 -fvisibility=hidden\" -DCMAKE_STATIC_LIBRARY_FLAGS=\"-g2 -m32 -arch i386\" -DCMAKE_OSX_SYSROOT=${SDK_DIR} -DPC_PCRE_INCLUDEDIR=${DIR}/installed-pcre/include -DPC_PCRE_LIBDIR=${DIR}/installed-pcre/lib   . &&
               make $NUM_PROCS &&
               mkdir -p ${DIR}/installed-opencollada/include/Math &&
               mkdir -p ${DIR}/installed-opencollada/include/libxml2/libxml &&
               find . -name COLLADA*.h -exec cp {} ${DIR}/installed-opencollada/include/ \; &&
               cp COLLADABaseUtils/include/Math/* ${DIR}/installed-opencollada/include/Math/ &&
               cp Externals/LibXML/include/libxml/*  ${DIR}/installed-opencollada/include/libxml2/libxml &&
               mkdir -p ${DIR}/installed-opencollada/lib &&
               cp -r lib ${DIR}/installed-opencollada/ &&
               mkdir -p ${DIR}/installed-opencollada/bin &&
               cp -r bin ${DIR}/installed-opencollada/" || \
    FAILED="$FAILED opencollada"
fi


################################################################################################################################
# Install NVTT
################################################################################################################################

#known not to work on mac, so disable for now
WITH_NVTT=false

if [[ -n "$INSTALLED_NVTT" ]] ; then
    make_symlink $INSTALLED_NVTT installed-nvtt
    WITH_NVTT=false
fi
if $WITH_NVTT ; then
    echo "Installing nvtt..."

    clean_dir nvtt
    clean_dir installed-nvtt
    user_eval "cd ${DIR} &&
               ( [ -e nvidia-texture-tools-2.0.8-1.tar.gz ] || curl -O http://nvidia-texture-tools.googlecode.com/files/nvidia-texture-tools-2.0.8-1.tar.gz ) &&
               tar -xf nvidia-texture-tools-2.0.8-1.tar.gz &&
               cd nvidia-texture-tools &&
               patch -p1 < ../nvtt-mac-rpath.patch &&
               patch -p1 < ../nvtt-mac-32bit.patch &&
               cmake -DCMAKE_INSTALL_PREFIX=${DIR}/installed-nvtt -DCMAKE_C_FLAGS=-fPIC -DCMAKE_CXX_FLAGS=-fPIC -DNVTT_SHARED=1 .
               make &&
               make install" || \
    FAILED="$FAILED nvtt"
fi


################################################################################################################################
# Install SQLite
################################################################################################################################

if [[ -n "$INSTALLED_SQLITE" ]] ; then
    make_symlink $INSTALLED_SQLITE installed-sqlite
    WITH_SQLITE=false
fi
if $WITH_SQLITE ; then
    echo "Installing sqlite..."

    clean_dir sqlite-autoconf-3070500
    clean_dir installed-sqlite
    user_eval "cd ${DIR} &&
               ( [ -e sqlite-autoconf-3070500.tar.gz ] || curl -O http://www.sqlite.org/sqlite-autoconf-3070500.tar.gz ) &&
               tar -xzvf sqlite-autoconf-3070500.tar.gz &&
               cd sqlite-autoconf-3070500 &&
               PATH=${DIR}/wrapper:${PATH} CFLAGS=\"-m32 -arch i386\" CXXFLAGS=\"-m32 -arch i386\" LDFLAGS=\"-m32 -arch i386\" ./configure --prefix=${DIR}/installed-sqlite --with-pic --disable-shared &&
               make &&
               make install" || \
    FAILED="$FAILED sqlite"
fi


################################################################################################################################
# Install pkgconfig
################################################################################################################################

if [[ -n "$INSTALLED_PKGCONFIG" ]] ; then
    make_symlink $INSTALLED_PKGCONFIG installed-pkgconfig
    WITH_PKGCONFIG=false
fi
if $WITH_PKGCONFIG ; then
    echo "Installing pkgconfig..."

    clean_dir pkg-config-0.25
    clean_dir installed-pkg-confg
    user_eval "cd ${DIR} &&
               ( [ -e pkg-config-0.25.tar.gz ] || curl -O http://pkgconfig.freedesktop.org/releases/pkg-config-0.25.tar.gz ) &&
               tar -xzvf pkg-config-0.25.tar.gz &&
               cd pkg-config-0.25 &&
               ./configure --prefix=${DIR}/installed-pkg-config &&
               make &&
               make install" || \
    FAILED="$FAILED pkgconfig"
fi

################################################################################################################################
# Install protobufs
################################################################################################################################

if [[ -n "$INSTALLED_PROTOBUFS" ]] ; then
    make_symlink $INSTALLED_PROTOBUFS installed-protobufs
    WITH_PROTOBUFS=false
fi
if $WITH_PROTOBUFS ; then
    echo "Installing protobufs..."

    clean_dir protobuf-2.3.0
    clean_dir installed-protobufs
    user_eval "cd ${DIR} &&
               ( [ -e protobuf-2.3.0.tar.bz2 ] || curl -O http://protobuf.googlecode.com/files/protobuf-2.3.0.tar.bz2 ) &&
               tar -xjvf protobuf-2.3.0.tar.bz2 &&
               cd protobuf-2.3.0 &&
               PATH=${DIR}/wrapper:${PATH} CC=${DIR}/wrapper/gcc CXX=${DIR}/wrapper/g++ CFLAGS=\"-arch i386 -m32\" CXXFLAGS=\"-arch i386 -m32\" ./configure --prefix=${DIR}/installed-protobufs &&
               make $NUM_PROCS &&
               make install" || \
    FAILED="$FAILED protobufs"
fi


################################################################################################################################
# Install antlr
################################################################################################################################

if [[ -n "$INSTALLED_ANTLR" ]] ; then
    make_symlink $INSTALLED_ANTLR installed-antlr
elif $WITH_ANTLR ; then
    echo "Installing ANTLR..."
    # Note that in the configure line we have some very ugly compiler settings, directly in CC and CXX. This is necessary because the appropriate settings aren't making it through to the link-time command, causing it to link against the wrong SDK.
    user_eval "cd ${DIR} &&
               ( [ -e libantlr3c-3.1.3.tar.gz ] || curl -O http://antlr.org/download/C/libantlr3c-3.1.3.tar.gz ) &&
               tar -zxf libantlr3c-3.1.3.tar.gz &&
               cd libantlr3c-3.1.3 &&
               PATH=${DIR}/wrapper:${PATH} CC=\"${DIR}/wrapper/gcc -isysroot ${SDK_DIR} -mmacosx-version-min=${SDK_VER} -m32 -arch i386 -fexceptions\" CXX=\"${DIR}/wrapper/g++ -isysroot ${SDK_DIR} -m32 -arch i386 -mmacosx-version-min=${SDK_VER}\" ./configure --prefix=${DIR}/installed-antlr --disable-shared --with-pic &&
               make $NUM_PROCS &&
               make install" || \
    FAILED="$FAILED antlr"
fi


################################################################################################################################
# Install gsl
################################################################################################################################

if [[ -n "$INSTALLED_GSL" ]] ; then
    make_symlink $INSTALLED_GSL installed-gsl
elif $WITH_GSL ; then
    echo "Installing GSL..."
    user_eval "cd ${DIR} &&
               ( [ -e gsl-1.14.tar.gz ] || curl -O http://ftp.wayne.edu/pub/gnu/gsl/gsl-1.14.tar.gz ) &&
               tar -zxf gsl-1.14.tar.gz &&
               cd gsl-1.14 &&
               PATH=${DIR}/wrapper:${PATH} CC=\"${DIR}/wrapper/gcc -isysroot ${SDK_DIR} -mmacosx-version-min=${SDK_VER}\" CXX=\"${DIR}/wrapper/g++ -isysroot ${SDK_DIR} -mmacosx-version-min=${SDK_VER}\" CFLAGS=\"-m32 -arch i386\" CXXFLAGS=\"-m32 -arch i386\" LDFLAGS=\"-m32 -arch i386\" ./configure --prefix=${DIR}/installed-gsl --with-pic &&
               make $NUM_PROCS &&
               make install" || \
    FAILED="$FAILED antlr"
fi


################################################################################################################################
# Install bullet
################################################################################################################################

if [[ -n "$INSTALLED_BULLET" ]] ; then
    make_symlink $INSTALLED_BULLET installed-bullet
elif $WITH_BULLET ; then
    echo "Installing Bullet..."
    clean_dir installed-bullet
    user_eval "cd ${DIR} &&
               ( [ -e bullet-2.78-r2387.tgz ] || curl -O http://bullet.googlecode.com/files/bullet-2.78-r2387.tgz ) &&
               tar -zxf bullet-2.78-r2387.tgz &&
               cd bullet-2.78 &&
               ./autogen.sh &&
               PATH=${DIR}/wrapper:${PATH} CC=\"${DIR}/wrapper/gcc -isysroot ${SDK_DIR} -mmacosx-version-min=${SDK_VER}\" CXX=\"${DIR}/wrapper/g++ -isysroot ${SDK_DIR} -mmacosx-version-min=${SDK_VER}\" CFLAGS=\"-m32 -arch i386\" CXXFLAGS=\"-m32 -arch i386\" LDFLAGS=\"-m32 -arch i386\" ./configure --prefix=${DIR}/installed-bullet --disable-demos &&
               make $NUMPROCS &&
               make install &&
               cp src/BulletDynamics/Dynamics/btActionInterface.h ${DIR}/installed-bullet/include/bullet/BulletDynamics/Dynamics/ &&
               echo // >>${DIR}/installed-bullet/include/bullet/BulletDynamics/Dynamics/btActionInterface.h" || \
    FAILED="$FAILED bullet"

fi


################################################################################################################################
# Install thrift
################################################################################################################################

if [[ -n "$INSTALLED_THRIFT" ]] ; then
    make_symlink $INSTALLED_THRIFT installed-thrift
    WITH_THRIFT=false
fi
if $WITH_THRIFT ; then
    echo "Installing thrift..."

    THRIFT_VERSION="0.8.0"
    clean_dir thrift-${THRIFT_VERSION}
    clean_dir installed-thrift
    # Separating these out to make the configure line clearer -- basically disabling all non-C support.
    # We should be able to add the following to reduce the number of code generators, but thrift's build seems to fail in their test/ directory if you add them.
    # --enable-gen-c_glib=no --enable-gen-java=no --enable-gen-as3=no --enable-gen-csharp=no --enable-gen-py=no --enable-gen-rb=no --enable-gen-perl=no --enable-gen-php=no --enable-gen-erl=no --enable-gen-cocoa=no --enable-gen-st=no --enable-gen-ocaml=no --enable-gen-hs=no --enable-gen-xsd=no --enable-gen-html=no --enable-gen-js=no --enable-gen-javame=no
    THRIFT_FEATURES="--with-csharp=no --with-java=no --with-erlang=no --with-python=no --with-perl=no --with-php=no --with-php_extension=no --with-ruby=no --with-haskell=no"
    # DON'T use $NUM_PROCS on make, something changed between 0.6.1
    # and 0.7.0 that causes it to fail sometimes with parallel make
    user_eval "cd ${DIR} &&
               ([ -e thrift-${THRIFT_VERSION}.tar.gz ] || wget  http://apache.mirrorcatalogs.com/thrift/${THRIFT_VERSION}/thrift-${THRIFT_VERSION}.tar.gz) &&
               tar -xzvf thrift-${THRIFT_VERSION}.tar.gz &&
               cd thrift-${THRIFT_VERSION} &&
               PATH=${DIR}/wrapper:${PATH} CC=${DIR}/wrapper/gcc CXX=${DIR}/wrapper/g++ ./configure --with-boost=${DIR}/installed-boost --with-pic ${THRIFT_FEATURES} --prefix=${DIR}/installed-thrift &&
               make &&
               make install" || \
    FAILED="$FAILED thrift"
fi


################################################################################################################################
# Install libcassandra
################################################################################################################################

if [[ -n "$INSTALLED_LIBCASSANDRA" ]] ; then
    make_symlink $INSTALLED_LIBCASSANDRA installed-libcassandra
    WITH_LIBCASSANDRA=false
fi
if $WITH_LIBCASSANDRA ; then
    echo "Installing libcassandra..."

    clean_dir installed-libcassandra
    # Note that we fix the revision so updates to.
    user_eval "cd ${DIR} &&
               ([ -e libcassandra.git ] || git clone https://github.com/sirikata/libcassandra.git libcassandra.git) &&
               cd libcassandra.git &&
               git pull &&
               ./config/autorun.sh &&
               PATH=${DIR}/wrapper:${PATH} CC=${DIR}/wrapper/gcc CXX=${DIR}/wrapper/g++ CXXFLAGS=\"-DT_GLOBAL_DEBUG_VIRTUAL=0 -Wno-variadic-macros -Wno-overloaded-virtual\" ./configure --with-pic --with-libthrift-prefix=${DIR}/installed-thrift --with-libboost_system-prefix=${DIR}/installed-boost --with-libboost_system-mt-prefix=${DIR}/installed-boost --with-boost-prefix=${DIR}/installed-boost/ --prefix=${DIR}/installed-libcassandra &&
               make clean &&
               make &&
               make install" || \
    FAILED="$FAILED libcassandra"
fi



################################################################################################################################
# Install yasm
################################################################################################################################

if [[ -n "$INSTALLED_YASM" ]] ; then
    make_symlink $INSTALLED_YASM installed-yasm
    WITH_YASM=false
fi
if $WITH_YASM ; then
    echo "Installing yasm..."

    YASM_VER="1.1.0"
    YASM_DIR="yasm-${YASM_VER}"
    YASM_ARCHIVE="yasm-${YASM_VER}.tar.gz"
    clean_dir installed-yasm
    user_eval "cd ${DIR} &&
               ([ -e ${YASM_ARCHIVE} ] || wget http://www.tortall.net/projects/yasm/releases/${YASM_ARCHIVE}) &&
               tar -xzvf ${YASM_ARCHIVE} &&
               cd ${YASM_DIR} &&
               PATH=${DIR}/wrapper:${PATH} CC=${DIR}/wrapper/gcc CXX=${DIR}/wrapper/g++ ./configure --prefix=${DIR}/installed-yasm --disable-debug --disable-dependency-tracking &&
               make $NUM_PROCS &&
               make install" || \
    FAILED="$FAILED yasm"
fi

################################################################################################################################
# Install ffmpeg
################################################################################################################################

if [[ -n "$INSTALLED_FFMPEG" ]] ; then
    make_symlink $INSTALLED_FFMPEG installed-ffmpeg
    WITH_FFMPEG=false
fi
if $WITH_FFMPEG ; then
    echo "Installing ffmpeg..."

    FFMPEG_VER="0.8.7"
    FFMPEG_DIR="ffmpeg-${FFMPEG_VER}"
    FFMPEG_ARCHIVE="ffmpeg-${FFMPEG_VER}.tar.bz2"
    clean_dir installed-ffmpeg
    # NOTE: Be careful about configuration options for ffmpeg due to
    # legal reasons. Unless you know what you're doing, do *not* use
    # --enable-gpl or --enable-nonfree. Also do *not* change the
    # settings for shared/static: we use shared libraries because
    # ffmpeg/it's libraries are LGPL, so we have to dynamically link
    # with them.
    #
    # ffmpeg.remove-omit-frame-pointer.patch -- disables
    #   -fomit-frame-pointer to avoid an llvm compiler failure.
    # --disable-mmx -- used because some mmx-optimized code also
    #   causes an llvm compiler failure.
    FFMPEG_BITNESS_FLAGS="-m32 -arch i386 -isysroot ${SDK_DIR} -mmacosx-version-min=${SDK_VER}"
    user_eval "cd ${DIR} &&
               ([ -e ${FFMPEG_ARCHIVE} ] || wget http://ffmpeg.org/releases/${FFMPEG_ARCHIVE}) &&
               tar -xjvf ${FFMPEG_ARCHIVE} &&
               cd ${FFMPEG_DIR} &&
               patch -p1 < ../ffmpeg.remove-omit-frame-pointer.patch &&
               PATH=${DIR}/wrapper:${DIR}/installed-yasm/bin:${PATH} ./configure --prefix=${DIR}/installed-ffmpeg --disable-static --enable-shared --arch=i386 \"--extra-cflags=${FFMPEG_BITNESS_FLAGS}\" \"--extra-ldflags=${FFMPEG_BITNESS_FLAGS}\" --disable-mmx &&
               PATH=${DIR}/wrapper:${DIR}/installed-yasm/bin:${PATH} make $NUM_PROCS &&
               make install" || \
    FAILED="$FAILED ffmpeg (required dependencies: yasm)"
fi



################################################################################################################################
# Finish
################################################################################################################################

if [ "x$FAILED" != "x" ]; then
    echo "Failed: $FAILED"
    exit -1
fi
